package com.xteam.xnetworkdisk.websocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Component
public class ProgressWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private WebSocketSessionManager sessionManager;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从 session 的属性中获取文件 MD5
        System.out.println(session.getAttributes());
        String fileMd5 = (String) session.getAttributes().get("md5");
        sessionManager.addSession(fileMd5, session);
        System.out.println("WebSocket connection established for fileMd5: " + fileMd5);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 从 session 的属性中获取文件 MD5
        String fileMd5 = (String) session.getAttributes().get("md5");
        sessionManager.removeSession(fileMd5);
        System.out.println("WebSocket connection closed for fileMd5: " + fileMd5);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        // 处理来自客户端的消息（如果有需要的话）
        System.out.println("Received message: " + message.getPayload());
    }

    public void sendProgressUpdate(String fileMd5, String progress) throws IOException {
        sessionManager.sendProgressUpdate(fileMd5, progress);
    }

    public void closeConnection(String fileMd5) throws IOException {
        sessionManager.closeSession(fileMd5);
        System.out.println("WebSocket connection closed");
    }
}
